<?php
namespace common\components;

use Monolog\Logger;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Formatter\HtmlFormatter;

 /**
 * 作者：d.coffee
 * 时间：2015-11-22
 * 功能：写入数据库handler拓展，消息
 */
class MessageHandler extends AbstractProcessingHandler
{
    private $initialized = false;
    private $model;

    public function __construct($model, $level = Logger::INFO, $bubble = true)
    {
        $this->model = $model;
        parent::__construct($level, $bubble);
    }

    protected function write(array $record)
    {
        if (!$this->initialized) {
            $this->initialize();
        }
        //入库
        foreach ( $record['context'] as $key=>$value ) {
            $this->model->$key = $value;
        }

        if ( $this->model->validate() ) {
            $this->model->save();  
        }
    }

    private function initialize()
    {
        $this->model->addtime = time();
    }

    /**
     * {@inheritdoc} 格式化日志结果(HTML)
     */
    public function handle(array $record)
    {
        if (!$this->isHandling($record)) {
            return false;
        }


        $record = $this->processRecord($record);
        $HtmlFormatter = new HtmlFormatter();
        $record['formatted'] = $HtmlFormatter->format($record);

        $this->write($record);

        return false === $this->bubble;
    }

    protected function processRecord(array $record)
    {
        if ($this->processors) {
            foreach ($this->processors as $processor) {
                $record = call_user_func($processor, $record);
            }
        }
        return $record;
    }
}